function setUpLoginPage() {
	var page = $("#loginPage");
	
	$("#link-signup", page).on("click", function(event) {
		event.preventDefault();

		var signupDialog = getTemplate("signupDialogTemplate");
		$("#signupEmail", signupDialog).on("keypress", function(event) {
			if (event.which === 13) {
				$("#signupButton", signupDialog.parent()).trigger("click");
			}
		});
		
		signupDialog.find("form").validate({
			rules : {
				signupEmail : {
					required : true,
					email : true
				}
			}
		});

		signupDialog.dialog({
			dialogClass : "noclose",
			closeOnEscape : true,
			modal : true,
			resizable : false,
			draggable : false,
			buttons : [ {
				id : "signupButton",
				text : "Sign up",
				click : function() {
					if ($(this).find("form").valid()) {
						var email = $(this).find("#signupEmail").val();
						$(this).dialog("close");
						signUp(email, showMessage, showErrorMessage);
					}
				}
			} ],
			close : function() {
				$(this).remove();
			}
		});
	});

	$("#forgotPassword", page).on("click", function(event) {
		event.preventDefault();
		
		var remindDialog = getTemplate("remindDialogTemplate");
		$("#remindEmail", remindDialog).on("keypress", function(event) {
			if (event.which === 13) {
				$("#remindButton", remindDialog.parent()).trigger("click");
			}
		});
		
		remindDialog.find("form").validate({
			rules : {
				remindEmail : {
					required : true,
					email : true
				}
			}
		});

		remindDialog.dialog({
			dialogClass : "noclose",
			closeOnEscape : true,
			modal : true,
			resizable : false,
			draggable : false,
			buttons : [ {
				id : "remindButton",
				text : "Remind me",
				click : function() {
					if ($(this).find("form").valid()) {
						var email = $(this).find("#remindEmail").val();
						$(this).dialog("close");
						remind(email);
					}
				}
			} ],
			close : function() {
				$(this).remove();
			}
		});
	});
	
	$("#signinForm", page).validate({
		rules : {
			email : {
				required : true,
				email : true
			},
			password : {
				required : true
			}
		}
	});
	
	$("#signIn", page).on("click", function(event) {
		event.preventDefault();

		var signinForm = $("#signinForm", page);
		if (signinForm.valid()) {
			var username = $("#email", signinForm).val();
			var password = $("#password", signinForm).val();
			signIn(username, password);
		}
	});
}

function tearDownLoginPage() {
	var page = $("#loginPage");
	$("#link-signup", page).off("click");
	$("#signIn", page).off("click");
	$("#forgotPassword", page).off("click");
}

function setUpConfirmRegisterPage() {
	var email = getUrlParameter("email");
	var token = getUrlParameter("token");
	
	$.ajax({
		type : "POST",
		url : getContextPath() + "/Confirm",
		data : {
			email : email,
			token : token
		},
		beforeSend : showSpinningWheel,
		success : function(response) {
			$("#spinningWheelDialog").dialog("close");

			if (response.success) {
				showMessage(response.message, redirectToLoginPage);
			} else {
				showErrorMessage(response.errorMessage, redirectToLoginPage);
			}
		},
		error : function(request) {
			$("#spinningWheelDialog").dialog("close");
			
			showErrorMessage("An error occurred. Please try again later.", redirectToLoginPage);
		}
	});
}

function tearDownConfirmRegisterPage() {
}

function setUpMainPage() {
	var page = $("#mainPage");

	$("button", page).button();
	
	$("#resetPassword", page).on("click", function() {
		$("<div><p>Are you sure you want to reset your password?</p></div>").dialog({
			dialogClass : "noclose noTitleBar",
			closeOnEscape : true,
			modal : true,
			resizable : false,
			draggable : false,
			buttons : [ 
			    {
			    	id : "okButton",
			    	text : "Ok",
			    	click : function() {
			    		$(this).dialog("close");
			    		resetPassword(applicationContext.email, applicationContext.accessToken);
			    	}
				}, 
				{
					id : "CancelButton",
					text : "Cancel",
					click : function() {
						$(this).dialog("close");
					}
				}
			],
			close : function() {
				$(this).remove();
			}
		});
	});
	
	$("#deleteAccount", page).on("click", function() {
		$("<div><p>Are you sure you want to delete your account?</p></div>").dialog({
			dialogClass : "noclose noTitleBar",
			closeOnEscape : true,
			modal : true,
			resizable : false,
			draggable : false,
			buttons : [ 
			    {
			    	id : "okButton",
			    	text : "Ok",
			    	click : function() {
			    		$(this).dialog("close");
			    		deleteAccount(applicationContext.email, applicationContext.accessToken);
			    	}
				}, 
				{
					id : "CancelButton",
					text : "Cancel",
					click : function() {
						$(this).dialog("close");
					}
				}
			],
			close : function() {
				$(this).remove();
			}
		});
	});

	$("#signOut", page).on("click", function() {
		signOut(applicationContext.email, applicationContext.accessToken);
	});
	
	$(".main-content", page).layout({
		west: {size: 250}, 
		south__paneSelector: ".south",
		west__paneSelector: ".west",
		center__paneSelector: ".center",
		center__childOptions: {
			west: {size: 300},
			west__paneSelector: ".center-west",
			center__paneSelector: ".center-center",
			center__childOptions: {
				center__paneSelector: ".center-center-center",
				south__paneSelector: ".center-center-south"
			}
		}
	});
	
	$("#sendMessage").button().on("click", function(event) {
		sendMessage();
	});

	$("#chatMessage").on("keydown", function(event) {
		if (event.keyCode == 13) {
			sendMessage();
		}
	});
	
	$("#refreshGroup").button().on("click", function(event) {
		currentGroupId = $(this).parent().attr("data-groupId");
		currentMsgHead = 0;
		clearTimeout(chatPollId);
		
		$("#chatMessageList").empty();
		$("#memberList").empty();
		
		pollGroupList();
	});
	
	$("#memberList").on("click", "button.kickUser", function(event) {
		$.ajax({
			url : getContextPath() + "/Group",
			type: "GET",
			data: {
				action: "kickGroup",
				user: $(this).attr("data-email"),
				email: applicationContext.email,
				accessToken: applicationContext.accessToken,
				groupId : currentGroupId
			},
			success : function(response) {
				if (response.success) {
					getMemberList();
				}
			}
		});
	});
	
	$("#groupList").on("click", "button.enterGroupChat", function(event) {
		currentGroupId = $(this).parent().attr("data-groupId");
		currentMsgHead = 0;
		clearTimeout(chatPollId);
		$("#chatMessageList").empty();
		
		getMemberList();
		pollChatMessages();
	});
	
	$("#groupList").on("click", "button.deleteGroup", function(event) {
		$.ajax({
			url : getContextPath() + "/Group",
			type: "POST",
			data: {
				action: "deleteGroup",
				email: applicationContext.email,
				accessToken: applicationContext.accessToken,
				groupId: $(this).parent().attr("data-groupId")
			},
			success : function(response) {
				if (response.success) {
					$("#chatMessageList").empty();
					$("#memberList").empty();
					
					pollGroupList();
				}
			}
		});
	});
	
	$("#createGroup").on("click", function(event) {
		var newGroupDialog = getTemplate("newGroupDialogTemplate");
		$("#groupName", newGroupDialog).on("keypress", function(event) {
			if (event.which === 13) {
				$("#createButton", newGroupDialog.parent()).trigger("click");
			}
		});
		
		newGroupDialog.find("form").validate({
			rules : {
				groupName : {
					required : true
				}
			}
		});

		newGroupDialog.dialog({
			dialogClass : "noclose",
			closeOnEscape : true,
			modal : true,
			resizable : false,
			draggable : false,
			buttons : [ {
				id : "createButton",
				text : "Create",
				click : function() {
					if ($(this).find("form").valid()) {
						$(this).dialog("close");
						createGroup($(this).find("#groupName").val());
					}
				}
			} ],
			close : function() {
				$(this).remove();
			}
		});
	});
	
	$("#inviteGroup").on("click", function(event) {
		$.ajax({
			url : getContextPath() + "/Group",
			type: "POST",
			data: {
				action: "myOwnGroup",
				email: applicationContext.email,
				accessToken: applicationContext.accessToken,
			},
			success : function(response) {
				if (response.success) {
					var inviteDialog = getTemplate("inviteDialogTemplate");
					
					inviteDialog.find("form").validate({
						rules : {
							groupName : {
								required : true
							},
							guest : {
								email: true,
								required : true
							}
						}
					});
					
					var input = inviteDialog.find("#group");
					$.each(response.groups, function(index, group) {
						$("<option></option").attr("value", group.id).html(group.name).appendTo(input);
					});

					inviteDialog.dialog({
						dialogClass : "noclose",
						closeOnEscape : true,
						modal : true,
						resizable : false,
						draggable : false,
						buttons : [ {
							id : "inviteButton",
							text : "Invite",
							click : function() {
								if ($(this).find("form").valid()) {
									$(this).dialog("close");

									$.ajax({
										url : getContextPath() + "/Group",
										type: "POST",
										data: {
											action: "sendInviteGroup",
											email: applicationContext.email,
											accessToken: applicationContext.accessToken,
											guest: $(this).find("#guest").val(),
											groupId: $(this).find("#group option:selected").val()
										},
										success : function(response) {
											if (response.success) {
												showMessage(response.message);
											} else {
												showErrorMessage(response.errorMessage);
											}
										}
									});
								}
							}
						} ],
						close : function() {
							$(this).remove();
						}
					});
				} else {
					showErrorMessage(response.errorMessage);
				}
			}
		});
	});
	
	pollGroupList();
}

function tearDownMainPage() {
	var page = $("#mainPage");
	$("button", page).off("click");
	clearTimeout(chatPollId);
}

function signUp(email, callbackSuccess, callbackFailure) {
	$.ajax({
		type : "POST",
		url : getContextPath() + "/Register",
		data : {
			email : email
		},
		beforeSend : showSpinningWheel,
		success : function(response) {
			$("#spinningWheelDialog").dialog("close");

			if (response.success) {
				callbackSuccess(response.message);
			} else {
				callbackFailure(response.errorMessage);
			}
		},
		error : function(request) {
			$("#spinningWheelDialog").dialog("close");

			callbackFailure("An error occurred. Please try again later.");
		}
	});
}

function signIn(email, password) {
	$.ajax({
		type : "POST",
		url : getContextPath() + "/Login",
		data : {
			email : email,
			password : password
		},
		beforeSend : showSpinningWheel,
		success : function(response) {
			$("#spinningWheelDialog").dialog("close");
			
			var signinForm = $("#signinForm", $("#loginPage"));
			$("p.error", signinForm).remove();

			if (response.success) {
				applicationContext.accessToken = response.accessToken;
				applicationContext.email = email;
				
				//load main page
				$("div[id$='Page'][id!='mainPage']").each(
					function(index, item) {
						var pageId = $(this).attr("id");
						$(this).hide(0, function() {
							applicationContext.pageControllers[pageId].tearDown();
						});
					});
				$("#mainPage").show(0, function() {
					applicationContext.pageControllers["mainPage"].setUp();
				});
			} else {
				var errorMessage = $("<p class='error'></p>");
				errorMessage.html(response.errorMessage);
				errorMessage.insertBefore($("#signIn", signinForm));
			}
		},
		error : function(request) {
			$("#spinningWheelDialog").dialog("close");
			
			var signinForm = $("#signinForm", $("#loginPage"));
			$("p.error", signinForm).remove();
			
			var errorMessage = $("<p class='error'></p>");
			errorMessage.html(response.errorMessage);
			errorMessage.insertBefore($("#signIn", signinForm));
		}
	});
}

function remind(email) {
	$.ajax({
		type : "POST",
		url : getContextPath() + "/Reminder",
		data : {
			email : email,
		},
		beforeSend : showSpinningWheel,
		success : function(response) {
			$("#spinningWheelDialog").dialog("close");
			
			if (response.success) {
				showMessage(response.message);
			} else {
				showErrorMessage(response.errorMessage);
			}
		},
		error : function(request) {
			$("#spinningWheelDialog").dialog("close");
			
			showErrorMessage("An error occurred. Please try again later.");
		}
	});
}

function resetPassword(email, accessToken) {
	$.ajax({
		type : "POST",
		url : getContextPath() + "/Reset",
		data : {
			email : email,
			accessToken : accessToken
		},
		beforeSend : showSpinningWheel,
		success : function(response) {
			$("#spinningWheelDialog").dialog("close");
			
			if (response.success) {
				showMessage(response.message);
			} else {
				showErrorMesssage(response.errorMessage);
			}
		},
		error : function(request) {
			$("#spinningWheelDialog").dialog("close");
			showErrorMessage("An error occurred. Please try again later.");
		}
	});
}

function deleteAccount(email, accessToken) {
	$.ajax({
		type : "POST",
		url : getContextPath() + "/Delete",
		data : {
			email : email,
			accessToken : accessToken
		},
		beforeSend : showSpinningWheel,
		success : function(response) {
			$("#spinningWheelDialog").dialog("close");
			
			if (response.success) {
				showMessage(response.message, redirectToLoginPage);
			} else {
				showErrorMesssage(response.errorMessage, redirectToLoginPage);
			}
		},
		error : function(request) {
			$("#spinningWheelDialog").dialog("close");
			
			showErrorMessage("An error occurred. Please try again later.");
		}
	});
}

function signOut(email, accessToken) {
	$.ajax({
		type : "POST",
		url : getContextPath() + "/Logout",
		data : {
			email : email,
			accessToken : accessToken
		},
		beforeSend : showSpinningWheel,
		success : function(response) {
			$("#spinningWheelDialog").dialog("close");
			
			if (response.success) {
				applicationContext.email = null;
				applicationContext.accessToken = null;
				redirectToLoginPage();
			} else {
				showErrorMesssage(response.errorMessage);
			}
		},
		error : function(request) {
			$("#spinningWheelDialog").dialog("close");
			
			showErrorMessage("An error occurred. Please try again later.");
		}
	});
}
